package org.dicker.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.dicker.dao.MessageDao;
import org.dicker.entity.MessageInfo;
import org.dicker.util.ORMUtil;

public class MessageDaoImpl implements MessageDao {

	@Override
	public List<MessageInfo> selectByList(String name,int page,int pageSize) {
		String sql="SELECT *,date_format(creat_time, '%Y-%m-%d %H:%I:%S') creat_time,"
				+ "date_format(update_time, '%Y-%m-%d %H:%I:%S') update_time from tb_message"
				+ " where 1=1";
		List<Object> valueList = new ArrayList<Object>();
		
		if(name!=null && !name.equals("")){
			sql+=" and message_title like ?";
			String wenhao="%"+name+"%";
			valueList.add(wenhao);
		}
		
		sql+=" ORDER BY creat_time desc";
		
		if(page!=-1 && pageSize!=-1){
			sql+=" LIMIT ?,?";
			valueList.add((page-1)*pageSize);
			valueList.add(pageSize);
		}
		
		return ORMUtil.getInstance().selectList(MessageInfo.class, sql, valueList.toArray());
	}

	@Override
	public int selectCount(String name) {
		String sql="SELECT count(*) from tb_message"
				+ " where 1=1";
		List<Object> valueList = new ArrayList<Object>();
		
		if(name!=null && !name.equals("")){
			sql+=" and message_title like ?";
			String wenhao="%"+name+"%";
			valueList.add(wenhao);
		}
		long value= (long) ORMUtil.getInstance().selectSingleValue("count(*)", sql, valueList.toArray());
		return (int) value;
	}

	@Override
	public int deleteById(int messageid) {
		String sql="DELETE FROM tb_message WHERE message_id=?";
		return ORMUtil.getInstance().executeDML(sql, messageid);
	}

	@Override
	public boolean addMessage(MessageInfo mInfo) {
		String sql="INSERT INTO tb_message(message_title,message_pic,author,content,creat_time) "
				+ " VALUES (?,?,?,?,NOW())";
		return ORMUtil.getInstance().executeDML(sql, mInfo.getMessage_title(),mInfo.getMessage_pic(),mInfo.getAuthor()
				,mInfo.getContent())>0;
	}

	@Override
	public MessageInfo selectByInfo(int id) {
		String sql="SELECT *,date_format(creat_time, '%Y-%m-%d %H:%I:%S') creat_time,"
				+ "date_format(update_time, '%Y-%m-%d %H:%I:%S') update_time from "
				+ " tb_message where message_id=?";
		
		List<MessageInfo> mList = ORMUtil.getInstance().selectList(MessageInfo.class, sql, id);
		return mList.size()>0? mList.get(0):null;
	}

	@Override
	public boolean updateById(MessageInfo mInfo) {
		String sql="update tb_message set message_title=?";
		List<Object> list = new ArrayList<Object>();
		
		list.add(mInfo.getMessage_title());
		if(mInfo.getMessage_pic()!=null && !mInfo.getMessage_pic().equals("")){
			sql+=",message_pic=?";
			list.add(mInfo.getMessage_pic());
		}
		sql+=",author=?,content=?,update_time=NOW() where message_id=?";
		
		list.add(mInfo.getAuthor());
		list.add(mInfo.getContent());
		list.add(mInfo.getMessage_id());
		
		return ORMUtil.getInstance().executeDML(sql, list.toArray())>0;
	}

}
